package bubble_sort

import "learning/gooop/sorting"

type tBubbleSorter struct {
}

func newBubbleSorter() sorting.ISorter {
	return &tBubbleSorter{}
}

func (me *tBubbleSorter) Sort(data []interface{}, fnCompare sorting.CompareFunction) []interface{} {
	if data == nil {
		return nil
	}

	size := len(data)
	if size <= 1 {
		return data
	}
	last := size - 1

	
	for i := 0;i < last;i++ {
		hit := false
		
		for j := last;j > i;j-- {
			prev := j - 1
			if fnCompare(data[prev], data[j]) == sorting.GREATER {
				data[j], data[prev] = data[prev], data[j]
				hit = true
			}
		}
		
		if !hit {
			// no changes
			break
		}
	} 
	
	return data
}

var BubbleSorter = newBubbleSorter()